package com.hzw.video.muxer

import android.media.MediaCodec
import android.util.Log
import com.hzw.video.extractor.AudioExtractor
import com.hzw.video.extractor.VideoExtractor
import java.nio.ByteBuffer
import kotlin.concurrent.thread

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/9/18 16:52
 *
 * @Description:
 *
 */
class MP4Repack(audioPath: String, videoPath: String, muxer: String) {

    private val audioExtractor = AudioExtractor(audioPath)
    private val videoExtractor = VideoExtractor(videoPath)

    private val muxer = MMuxer(muxer)

    fun start() {
        val audioFormat = audioExtractor.getFormat()

        if (audioFormat == null) {
            muxer.setNoAudio()
        } else {
            muxer.addAudioTrack(audioFormat)
        }

        val videoFormat = videoExtractor.getFormat()

        if (videoFormat == null) {
            muxer.setNoVideo()
        } else {
            muxer.addVideoTrack(videoFormat)
        }

        thread {
            val buffer = ByteBuffer.allocate(500 * 1024)
            val bufferInfo = MediaCodec.BufferInfo()

            if (audioFormat != null) {
                var size = audioExtractor.readBuffer(buffer)
                while (size > 0) {
                    bufferInfo.set(
                        0,
                        size,
                        audioExtractor.getCurrentTimestamp(),
                        audioExtractor.getSampleFlag()
                    )
                    muxer.writeAudioData(buffer, bufferInfo)
                    size = audioExtractor.readBuffer(buffer)
                }
            }

            if (videoFormat != null) {
                var size = videoExtractor.readBuffer(buffer)
                while (size > 0) {
                    bufferInfo.set(
                        0,
                        size,
                        videoExtractor.getCurrentTimestamp(),
                        videoExtractor.getSampleFlag()
                    )
                    muxer.writeVideoData(buffer, bufferInfo)
                    size = videoExtractor.readBuffer(buffer)
                }
            }

            audioExtractor.stop()
            videoExtractor.stop()
            muxer.release()

            Log.i("hzw", "视频生成完成")
        }
    }
}